package startup

import (
	prom "github.com/go-kratos/kratos/contrib/metrics/prometheus/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/metadata"
	"github.com/go-kratos/kratos/v2/middleware/metrics"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/middleware/validate"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/go-kratos/kratos/v2/transport/http/pprof"
	"gotham-plan-manage/internal/conf"
	"gotham-plan-manage/internal/interfaces/facade"
	"gotham-plan-manage/pkg/interceptor"
	"gotham-plan-manage/proto/gotham-plan-manage-proto/plan"
	"gotham-plan-manage/proto/gotham-plan-manage-proto/task"
	"time"
)

// NewHTTPServer new an HTTP startup.
func NewHTTPServer(c *conf.Server, planApi *facade.PlanServer, taskApi *facade.TaskServer, logger log.Logger) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			validate.Validator(),
			metadata.Server(),
			interceptor.Auth(),
			logging.Server(logger),
			tracing.Server(),
			metrics.Server(
				metrics.WithSeconds(prom.NewHistogram(conf.MetricSeconds)),
				metrics.WithRequests(prom.NewCounter(conf.MetricRequests)),
			),
		),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	//if c.Http.Timeout != nil {
	//	opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	//}
	// 设置10s超时
	opts = append(opts, http.Timeout(60*time.Second))
	srv := http.NewServer(opts...)
	plan.RegisterPlanApiHTTPServer(srv, planApi)
	task.RegisterTodoTaskApiHTTPServer(srv, taskApi)
	srv.HandlePrefix("/", pprof.NewHandler())
	return srv
}
